package org.rency.crawler.fetch.handler.impl;

import java.util.List;
import javax.annotation.Resource;
import org.rency.crawler.common.enums.ReturnCode;
import org.rency.crawler.common.exception.CrawlerException;
import org.rency.crawler.domain.FetchResponse;
import org.rency.crawler.domain.state.FetchStatus;
import org.rency.crawler.fetch.handler.AbstractFetchHandler;
import org.rency.crawler.fetch.helper.FetchCarrier;
import org.rency.crawler.fetch.service.policy.PolicyService;
import org.springframework.stereotype.Component;

/**
 * 描述: ${TODO}<br>
 * 最近修改时间:2017/11/22 11:44<br>
 *
 * @author CaiyuRen
 * @version V1.0
 * @since 2017/11/22 11:44
 */
@Component
public class FetchPolicyHandler extends AbstractFetchHandler {

  @Resource(name = "policyServices")
  private List<PolicyService> policyServices;

  @Override
  protected String getHandlerName() {
    return "抓取策略";
  }

  @Override
  protected void onHandler(FetchCarrier carrier) throws CrawlerException {
    for(PolicyService policy : policyServices){
      logger.info("执行策略校验[{}],{}.",policy.getPolicyName(),carrier.getRequest().getFetchUri());
      if(!policy.accept(carrier)){
        logger.warn("[{}:{}]未通过!",this.getHandlerName(),policy.getPolicyName());
        carrier.setResponse(FetchResponse.fail(ReturnCode.POLICY_REJECT,policy.getPolicyName()));
        if(policy.retrySupport()){
          carrier.getFetchState().setFsStatus(FetchStatus.EXCEPTION);
        }else{
          carrier.getFetchState().setFsStatus(FetchStatus.FAILED);
        }
        break;
      }
      carrier.getFetchState().setFsStatus(FetchStatus.SUCCESS);
    }
  }
}
